import 'package:flutter/material.dart';
import '../../model/post.dart';

/**
 * 数据表格
 */
class DataTableDemo extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return DataTableStateDemo();
  }
}

class DataTableStateDemo extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return DataTableState();
  }
}

class DataTableState extends State<DataTableStateDemo> {
  //排序列的角标
  int _sortColumnIndex = 0;

  // 升序还降序
  bool _sortAscending = false;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('DataTableDemo'),
        elevation: 0.0,
      ),
      body: Container(
        padding: EdgeInsets.all(8.0),
        child: ListView(
          children: <Widget>[
            DataTable(
              //排序的列
              sortColumnIndex: _sortColumnIndex,
              //升序还是降序：true 降序；
              sortAscending: _sortAscending,
              columns: [
                DataColumn(
                  label: Text('Title'),
                  onSort: (int index, bool ascending) {
                    debugPrint("ascending.Title: $index,$ascending");
                    change(index, ascending);
                  },
                ),
                DataColumn(
                  label: Text('Author'),
                  onSort: (int index, bool ascending) {
                    debugPrint("ascending.Author: $index,$ascending");
                    change(index, ascending);
                  },
                ),
                DataColumn(
                  label: Text('Image'),
                ),
              ],
              rows: postList.map((post) {
                return DataRow(
                    selected: post.selected,
                    onSelectChanged: (selected) {
                      setState(() {
                        if (selected != post.selected) {
                          post.selected = selected;
                        }
                      });
                    },
                    cells: [
                      DataCell(Text(post.title)),
                      DataCell(Text(post.author)),
                      DataCell(Image.network(post.imageUrl)),
                    ]);
              }).toList(),
            ),
          ],
        ),
      ),
    );
  }

  void change(int index, bool ascending) {
    setState(() {
      _sortColumnIndex = index;
      _sortAscending = ascending;
      //按照title的长度排列
      postList.sort((a, b) {
        if (!ascending) {
          final c = a;
          a = b;
          b = c;
        }
        switch (index) {
          case 0:
            return a.title.length.compareTo(b.title.length);
            break;
          case 1:
            return a.author.length.compareTo(b.author.length);
            break;
        }
      });
    });
  }
}
